package com.zjun.demo.ruleview

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.VectorDrawable
import android.text.TextPaint
import android.util.AttributeSet
import android.util.TypedValue
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.ScaleGestureDetector.OnScaleGestureListener
import android.view.VelocityTracker
import android.view.View
import android.view.ViewConfiguration
import android.widget.Scroller
import androidx.annotation.DrawableRes
import androidx.annotation.IntRange
import androidx.core.content.ContextCompat
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.zjun.demo.ruleview.TimeRuleView.TimePart
import kotlin.math.abs


class MyTimeRuleView : View {

    companion object {

        const val LOG_ENABLE = true

        /**
         * 最大小时数
         */
        const val MAX_TIME_VALUE = 24 * 3600

    }


    /**
     * 文字与指示器的间隔
     */
    private var gradationTextAndIndicatorGap: Float = 0f

    private var bgColor = 0

    /**
     * 刻度颜色
     */
    private var gradationColor = 0

    /**
     * 时间块的高度
     */
    private var partHeight = 0f

    /**
     * 时间块的颜色
     */
    private var partColor = 0

    /**
     * 刻度宽度
     */
    private var gradationWidth = 0f

    /**
     * 秒、分、时刻度的长度
     */
    private var secondLen = 0f
    private var minuteLen = 0f
    private var hourLen = 0f

    /**
     * 刻度数字文字颜色
     */
    private var gradationTextColor = 0

    /**
     * 刻度数字文字大小
     */
    private var gradationTextSize = 0f

    /**
     * 刻度数值与时刻度的距离
     */
    private var gradationTextGap = 0f

    /**
     * 刻度数字文字高度
     */
    private var gradationTextHeight: Float = 0f


    /**
     * 当前时间，单位：s
     */
    @IntRange(from = 0, to = TimeRuleView.MAX_TIME_VALUE.toLong())
    private var currentTime = 0

    /**
     * 指针颜色
     */
    private var indicatorColor = 0

    /**
     * 指针上三角形的边长
     */
    private var indicatorTriangleSideLen = 0f

    /**
     * 指针的宽度
     */
    private var indicatorWidth = 0f

    /**
     * 指针的高度
     */
    private var indicatorHeight = 0f

    /**
     * 用于绘制三角型的路径
     */
    private val mTrianglePath: Path = Path()

    /**
     * 三角型的高度
     */
    var triangleHeight = 10

    /**
     * 三角型的底边
     */
    var triangleBottomEdge = 10

    /**
     * 时间段
     */
    private var mTimePartList: List<TimePart>? = null

    private val mPaint = Paint()

    /**
     *
     */
    private lateinit var mMagnifyBitmap: Bitmap

    private lateinit var mReduceBitmap: Bitmap

    private var mBitmapRect: Rect = Rect()

    /**
     * 仅仅做显示的区域,并非真实的点击区域,因为有padding，会比真实点击区域小一点
     */
    private var mBitmapProxyRect: Rect = Rect()

    /**
     * 放大的真实点击区域
     */
    private var mMagnifyBitmapRect: Rect = Rect()

    /**
     * 缩小的真实点击区域
     */
    private var mReduceBitmapRect: Rect = Rect()

    /**
     * 宽度一半
     */
    private var mHalfWidth = 0

    /**
     * 当前时间与 00:00 的距离值
     */
    private var mCurrentDistance = 0f

    /**
     * 与 [.mPerTextCounts] 对应的阈值，在此阈值与前一个阈值之间，则使用此阈值对应的间隔数值
     * 如：1.5f 代表 4*60 对应的阈值，如果 mScale >= 1.5f && mScale < 1.8f，则使用 4*60
     *
     * 这些数值，都是估算出来的
     */
    private val mPerCountScaleThresholds = floatArrayOf(
        6f, 3.6f, 1.8f, 1.5f,  // 10s/unit: 最大值, 1min, 2min, 4min
        0.8f, 0.4f,  // 1min/unit: 5min, 10min
        0.25f, 0.125f,  // 5min/unit: 20min, 30min
        0.07f, 0.04f, 0.03f, 0.025f, 0.02f, 0.015f // 15min/unit: 1h, 2h, 3h, 4h, 5h, 6h
    )

    /**
     * 数值显示间隔,一共13级,第一级最大值,不包括
     */
    private val mPerTextCounts = intArrayOf(
        60, 60, 2 * 60, 4 * 60,  // 10s/unit: 最大值, 1min, 2min, 4min
        5 * 60, 10 * 60,  // 1min/unit: 5min, 10min
        20 * 60, 30 * 60,  // 5min/unit: 20min, 30min
        3600, 2 * 3600, 3 * 3600, 4 * 3600, 5 * 3600, 6 * 3600 // 15min/unit
    )

    /**
     * 数值文字宽度的一半：时间格式为“00:00”，所以长度固定
     */
    private var mTextHalfWidth = 0f

    /**
     * 绘制文字的画笔
     */
    private var mTextPaint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)

    /**
     * 默认索引值
     */
    private var mPerTextCountIndex = 4

    /**
     * 最小单位对应的单位秒数值，一共四级: 10s、1min、5min、15min
     * 与 [.mPerTextCounts] 和 [.mPerCountScaleThresholds] 对应的索引值
     *
     * 可以组合优化成数组
     */
    private val mUnitSeconds = intArrayOf(
        10, 10, 10, 10,
        60, 60,
        5 * 60, 5 * 60,
        15 * 60, 15 * 60, 15 * 60, 15 * 60, 15 * 60, 15 * 60
    )

    /**
     * 一格代表的秒数。默认1min
     */
    private var mUnitSecond = mUnitSeconds[mPerTextCountIndex]

    /**
     * 1s对应的间隔，比较好估算
     */
    private val mOneSecondGap = dp2px(12f) / 60f

    /**
     * 当前最小单位秒数值对应的间隔
     */
    private var mUnitGap: Float = mOneSecondGap * 60

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initAttrs(attrs)
        init(context)
        initScaleGestureDetector(context)

        mTextHalfWidth = mTextPaint.measureText("00:00") * .5f
        val viewConfiguration = ViewConfiguration.get(context)
        SCROLL_SLOP = viewConfiguration.scaledTouchSlop
        MIN_VELOCITY = viewConfiguration.scaledMinimumFlingVelocity
        MAX_VELOCITY = viewConfiguration.scaledMaximumFlingVelocity

        calculateValues()
    }

    private fun calculateValues() {
        mCurrentDistance = currentTime / mUnitSecond * mUnitGap
    }

    private fun init(context: Context) {
        mTextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
        mTextPaint.textSize = gradationTextSize
        mTextPaint.color = gradationTextColor
        val fontMetrics = mTextPaint.fontMetrics
        gradationTextHeight = fontMetrics.descent - fontMetrics.ascent
        descent = fontMetrics.descent+fontMetrics.bottom
        mTextHalfWidth = mTextPaint.measureText("00:00") * .5f

        mScroller = Scroller(context)
    }

    var descent:Float = 0f

    @SuppressLint("CustomViewStyleable")
    fun initAttrs(attrs: AttributeSet?) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.TimeRuleView)
        mMagnifyBitmap = getBitmapFromDrawable(R.drawable.svg80)
        mReduceBitmap = getBitmapFromDrawable(R.drawable.svg81)
        ta.use {
            bgColor = ta.getColor(R.styleable.TimeRuleView_zjun_bgColor, Color.parseColor("#EEEEEE"))
            gradationColor = ta.getColor(R.styleable.TimeRuleView_zjun_gradationColor, Color.GRAY)
            partHeight = ta.getDimension(R.styleable.TimeRuleView_trv_partHeight, dp2px(20f).toFloat())
            partColor = ta.getColor(R.styleable.TimeRuleView_trv_partColor, Color.parseColor("#4D17C8B7"))
            gradationWidth = ta.getDimension(R.styleable.TimeRuleView_trv_gradationWidth, 1f)
            secondLen = ta.getDimension(R.styleable.TimeRuleView_trv_secondLen, dp2px(3f).toFloat())
            minuteLen = ta.getDimension(R.styleable.TimeRuleView_trv_minuteLen, dp2px(5f).toFloat())
            hourLen = ta.getDimension(R.styleable.TimeRuleView_trv_hourLen, dp2px(10f).toFloat())
            gradationTextColor = ta.getColor(R.styleable.TimeRuleView_trv_gradationTextColor, Color.parseColor("#999999"))
            gradationTextSize = ta.getDimension(R.styleable.TimeRuleView_trv_gradationTextSize, sp2px(12f).toFloat())
            gradationTextGap = ta.getDimension(R.styleable.TimeRuleView_trv_gradationTextGap, dp2px(2f).toFloat())
            currentTime = ta.getInt(R.styleable.TimeRuleView_trv_currentTime, 0)
            indicatorTriangleSideLen = ta.getDimension(R.styleable.TimeRuleView_trv_indicatorTriangleSideLen, dp2px(15f).toFloat())

            indicatorHeight = ta.getDimension(R.styleable.TimeRuleView_trv_indicatorHeight, dp2px(30f).toFloat())
            triangleBottomEdge = ta.getDimensionPixelSize(R.styleable.TimeRuleView_trv_indicatorTriangleBottomEdgeHeight, dp2px(13f))
            triangleHeight = ta.getDimensionPixelSize(R.styleable.TimeRuleView_trv_indicatorTriangleHeight, dp2px(8f))
            gradationTextAndIndicatorGap = ta.getDimension(R.styleable.TimeRuleView_trv_gradationTextAndIndicatorGap, dp2px(10f).toFloat())

            indicatorWidth = ta.getDimension(R.styleable.TimeRuleView_zjun_indicatorLineWidth, dp2px(2f).toFloat())
            indicatorColor = ta.getColor(R.styleable.TimeRuleView_zjun_indicatorLineColor, Color.parseColor("#17C8B7"))


        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        mHalfWidth = widthSize shr 1
        //最小高度 = 三角高度+刻度高度+文字与刻度的间隔+文字高度+文字与竖线的间隔+竖线高度
        val minHeight = (hourLen.toInt()).coerceAtLeast(triangleHeight) + gradationTextGap + gradationTextHeight + gradationTextAndIndicatorGap + indicatorHeight
        val newHeightMeasureSpec = when (heightMode) {
            MeasureSpec.UNSPECIFIED,
            MeasureSpec.AT_MOST -> {
                MeasureSpec.makeMeasureSpec(minHeight.toInt(), MeasureSpec.EXACTLY)
            }

            else -> {
                MeasureSpec.makeMeasureSpec(heightSize.coerceAtLeast(minHeight.toInt()), MeasureSpec.EXACTLY)
            }
        }
        setMeasuredDimension(widthMeasureSpec, newHeightMeasureSpec)
    }

    /**
     * 缩放手势检测器
     */
    private lateinit var mScaleGestureDetector: ScaleGestureDetector

    private fun initScaleGestureDetector(context: Context) {
        mScaleGestureDetector = ScaleGestureDetector(context, object : OnScaleGestureListener {
            /**
             * 缩放被触发(会调用0次或者多次)，
             * 如果返回 true 则表示当前缩放事件已经被处理，检测器会重新积累缩放因子
             * 返回 false 则会继续积累缩放因子。
             */
            override fun onScale(detector: ScaleGestureDetector): Boolean {
                val scaleFactor = detector.scaleFactor
                val maxScale = mPerCountScaleThresholds[0]
                val minScale = mPerCountScaleThresholds[mPerCountScaleThresholds.size - 1]
                if (scaleFactor > 1 && mScale >= maxScale) {
                    // 已经放大到最大值
                    return true
                } else if (scaleFactor < 1 && mScale <= minScale) {
                    // 已经缩小到最小值
                    return true
                }
                mScale *= scaleFactor
                mScale = minScale.coerceAtLeast(maxScale.coerceAtMost(mScale))
                mPerTextCountIndex = findScaleIndex(mScale)
                mUnitSecond = mUnitSeconds[mPerTextCountIndex]
                mUnitGap = mScale * mOneSecondGap * mUnitSecond
                mCurrentDistance = currentTime.toFloat() / mUnitSecond * mUnitGap
                invalidate()
                return true
            }

            override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
                isScaling = true
                return true
            }

            override fun onScaleEnd(detector: ScaleGestureDetector) {
                isScaling = false
            }
        })
    }

    /**
     * 默认mScale为1
     */
    private var mScale = 1f

    private var isScaling = false

    private lateinit var mScroller: Scroller

    private lateinit var mVelocityTracker: VelocityTracker

    /**
     * 二分法查找缩放值对应的索引值
     */
    private fun findScaleIndex(scale: Float): Int {
        val size = mPerCountScaleThresholds.size
        var min = 0
        var max = size - 1
        var mid = min + max shr 1
        while (!(scale >= mPerCountScaleThresholds[mid] && scale < mPerCountScaleThresholds[mid - 1])) {
            if (scale >= mPerCountScaleThresholds[mid - 1]) {
                // 因为值往小区，index往大取，所以不能为mid -1
                max = mid
            } else {
                min = mid + 1
            }
            mid = min + max shr 1
            if (min >= max) {
                break
            }
            if (mid == 0) {
                break
            }
        }
        return mid
    }

    private var mInitialX = 0
    private var mLastX = 0
    private var mLastY:Int = 0
    private var isMoving = false

    private var SCROLL_SLOP = 0
    private var MIN_VELOCITY = 0
    private var MAX_VELOCITY = 0

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val actionIndex = event.actionIndex
        val pointerId = event.getPointerId(actionIndex)
        val actionMasked = event.actionMasked
        val action = event.action
        val pointerCount = event.pointerCount
        val x = event.x.toInt()
        val y = event.y.toInt()
        mScaleGestureDetector.onTouchEvent(event)
        if (!this::mVelocityTracker.isInitialized) {
            mVelocityTracker = VelocityTracker.obtain()
        }
        mVelocityTracker.addMovement(event)
        run {
            when (actionMasked) {
                MotionEvent.ACTION_DOWN -> {
                    isMoving = false
                    mInitialX = x
                    if (!mScroller.isFinished) {
                        mScroller.forceFinished(true)
                    }
                }

                MotionEvent.ACTION_POINTER_DOWN -> {
                    // 只要第二手指按下，就禁止滑动
                    isScaling = true
                    isMoving = false
                }

                MotionEvent.ACTION_MOVE -> {
                    if (isScaling) {
                        return@run
                    }
                    val dx: Int = x - mLastX
                    if (!isMoving) {
                        val dy: Int = y - mLastY
                        if (abs(x - mInitialX) <= SCROLL_SLOP || abs(dx) <= abs(dy)) {
                            return@run
                        }
                        isMoving = true
                    }
                    mCurrentDistance -= dx.toFloat()
                    computeTime()
                }

                MotionEvent.ACTION_UP -> {
                    if (isScaling || !isMoving) {
                        return@run
                    }
                    mVelocityTracker.computeCurrentVelocity(1000, MAX_VELOCITY.toFloat())
                    val xVelocity = mVelocityTracker.xVelocity.toInt()
                    if (abs(xVelocity) >= MIN_VELOCITY) {
                        // 惯性滑动
                        val maxDistance = (MAX_TIME_VALUE / mUnitGap * mUnitGap).toInt()
                        mScroller.fling(mCurrentDistance.toInt(), 0, -xVelocity, 0, 0, maxDistance, 0, 0)
                        invalidate()
                    }
                }

                MotionEvent.ACTION_POINTER_UP -> {
                    // 两个中的有一个手指被抬起，允许滑动。同时把未抬起的手机当前位置赋给初始X
                    isScaling = false
                    val restIndex = if (actionIndex == 0) 1 else 0
                    mInitialX = event.getX(restIndex).toInt()
                }

                else -> {}
            }
        }
        mLastX = x
        mLastY = y
        return true
    }

    private var mListener: OnTimeChangedListener? = null


    interface OnTimeChangedListener {
        fun onTimeChanged(newTimeValue: Int)
    }

    /**
     * 设置时间变化监听事件
     * @param listener 监听回调
     */
    fun setOnTimeChangedListener(listener: OnTimeChangedListener) {
        mListener = listener
    }

    private fun computeTime() {
        // 不用转float，肯定能整除
        val maxDistance = MAX_TIME_VALUE / mUnitSecond * mUnitGap
        // 限定范围
        mCurrentDistance = maxDistance.coerceAtMost(0f.coerceAtLeast(mCurrentDistance))
        currentTime = (mCurrentDistance / mUnitGap * mUnitSecond).toInt()
        if (mListener != null) {
            mListener?.onTimeChanged(currentTime)
        }
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        drawTimeParts(canvas)
        drawRule(canvas)
        drawScaleButton(canvas)
        drawableTriangle(canvas)
    }

    /**
     * 设置时间块（段）集合
     * @param timePartList 时间块集合
     */
    fun setTimePartList(timePartList: List<TimePart>) {
        mTimePartList = timePartList
        postInvalidate()
    }

    /**
     * 绘制刻度
     */
    private fun drawRule(canvas: Canvas) {

        val gap = (height*0.1f).toInt()
        val bitmapHeight = (height - gap*3)/2
        val marginRight = dp2px(20f)
        mMagnifyBitmapRect.set(width - marginRight - bitmapHeight, gap, width - marginRight, gap + bitmapHeight)



        mPaint.color = gradationColor
        mPaint.strokeWidth = gradationWidth
        val perTextCount = mPerTextCounts[mPerTextCountIndex]
        // 刻度
        var start = 0
        var offset: Float = mHalfWidth - mCurrentDistance

        while (start <= MAX_TIME_VALUE) {
            // 刻度
            if (start % 3600 == 0) {
                // 时刻度
                canvas.drawLine(offset, height.toFloat(), offset, height - hourLen, mPaint)
            } else if (start % 60 == 0) {
                // 分刻度
                canvas.drawLine(offset, height.toFloat(), offset, height - minuteLen, mPaint)
            } else {
                // 秒刻度
                canvas.drawLine(offset, height.toFloat(), offset, height - secondLen, mPaint)
            }
            // 时间数值
            if (start % perTextCount == 0) {
                val text = formatTimeHHmm(start)
                val textXRight = offset + mTextHalfWidth
                if(textXRight>mMagnifyBitmapRect.left){
                    mTextPaint.color = Color.TRANSPARENT

                }else{
                    mTextPaint.color = gradationColor
                }
                canvas.drawText(text, offset - mTextHalfWidth, height - (hourLen.toInt()).coerceAtLeast(triangleHeight) - gradationTextGap - descent, mTextPaint)
            }
            start += mUnitSecond
            offset += mUnitGap
        }
    }

    /**
     * 绘制三角型 与 指针
     */
    private fun drawableTriangle(canvas: Canvas) {
        //绘制指针
        mPaint.reset()
        mPaint.isAntiAlias = true
        mPaint.color = indicatorColor
        mPaint.strokeWidth = indicatorWidth
        val x = (width - indicatorWidth) / 2
        canvas.drawLine(x, 0f, x, indicatorHeight, mPaint)

        //绘制三角形
        mPaint.reset()
        mPaint.isAntiAlias = true
        mPaint.color = indicatorColor
        val startPointX = (width - triangleBottomEdge) / 2f
        val startPointY = height.toFloat()
        mTrianglePath.moveTo(startPointX, startPointY)
        mTrianglePath.lineTo(startPointX + triangleBottomEdge, startPointY)
        mTrianglePath.lineTo(startPointX + triangleBottomEdge / 2, (height - triangleHeight).toFloat())
        mTrianglePath.close()
        canvas.drawPath(mTrianglePath, mPaint)
    }

    /**
     * 绘制缩放按键
     */
    private fun drawScaleButton(canvas: Canvas) {
        val gap = (height*0.1f).toInt()
        val bitmapHeight = (height - gap*3)/2
        val marginRight = dp2px(20f)
        mMagnifyBitmapRect.set(width - marginRight - bitmapHeight, gap, width - marginRight, gap + bitmapHeight)

        mPaint.reset()
        mBitmapRect.set(0, 0, mMagnifyBitmap.width, mMagnifyBitmap.height)
        mBitmapProxyRect.set(width - marginRight - bitmapHeight, gap, width - marginRight, gap + bitmapHeight)
        mMagnifyBitmapRect.set(width - marginRight - bitmapHeight, gap, width - marginRight, gap + bitmapHeight)
        canvas.drawBitmap(mMagnifyBitmap, mBitmapRect, mBitmapProxyRect, mPaint)

        mBitmapRect.set(0, 0, mReduceBitmap.width, mReduceBitmap.height)
        mBitmapProxyRect.set(width - marginRight - bitmapHeight, height - gap - bitmapHeight, width - marginRight, height - gap)
        mReduceBitmapRect.set(width - marginRight - bitmapHeight, height - gap - bitmapHeight, width - marginRight, height - gap)
        canvas.drawBitmap(mReduceBitmap, mBitmapRect, mBitmapProxyRect, mPaint)
    }

    /**
     * 绘制时间段
     */
    private fun drawTimeParts(canvas: Canvas) {
        if (mTimePartList == null) {
            return
        }
        // 不用矩形，直接使用直线绘制
        mPaint.strokeWidth = height.toFloat()
        mPaint.color = partColor
        var start: Float
        var end: Float
        val halfPartHeight = height * .5f
        val secondGap = mUnitGap / mUnitSecond
        var i = 0
        val size: Int = mTimePartList!!.size
        while (i < size) {
            val timePart: TimePart = mTimePartList!![i]
            start = mHalfWidth - mCurrentDistance + timePart.startTime * secondGap
            end = mHalfWidth - mCurrentDistance + timePart.endTime * secondGap
            canvas.drawLine(start, halfPartHeight, end, halfPartHeight, mPaint)
            i++
        }
    }

    /**
     * 格式化时间 HH:mm
     * @param timeValueParam 具体时间值
     * @return 格式化后的字符串，eg：3600 to 01:00
     */
    fun formatTimeHHmm(@IntRange(from = 0, to = TimeRuleView.MAX_TIME_VALUE.toLong()) timeValueParam: Int): String {
        var timeValue = timeValueParam
        if (timeValue < 0) {
            timeValue = 0
        }
        val hour = timeValue / 3600
        val minute = timeValue % 3600 / 60
        val sb = StringBuilder()
        if (hour < 10) {
            sb.append('0')
        }
        sb.append(hour).append(':')
        if (minute < 10) {
            sb.append('0')
        }
        sb.append(minute)
        return sb.toString()
    }

    override fun computeScroll() {
        if (mScroller.computeScrollOffset()) {
            mCurrentDistance = mScroller.currX.toFloat()
            computeTime()
        }
    }

    private fun dp2px(dp: Float): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics)
            .toInt()
    }

    private fun sp2px(sp: Float): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, resources.displayMetrics)
            .toInt()
    }

    private fun getBitmapFromDrawable(@DrawableRes drawableId: Int): Bitmap {
        return when (val drawable = ContextCompat.getDrawable(context, drawableId)) {
            is BitmapDrawable -> {
                drawable.bitmap
            }

            is VectorDrawable, is VectorDrawableCompat -> {
                val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
                val canvas = Canvas(bitmap)
                drawable.setBounds(0, 0, canvas.width, canvas.height)
                drawable.draw(canvas)
                bitmap
            }

            else -> {
                throw IllegalArgumentException("unsupported drawable type")
            }
        }
    }


}